//
//  ServerViewController.swift
//  Wmsmobile
//
//  Created by wangshuning on 16/8/1.
//  Copyright © 2016年 hddden. All rights reserved.
//

import UIKit

import MMDrawerController

import SVProgressHUD
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}


class ServerViewController: UIViewController, UITextFieldDelegate , AVQRCodeViewManagerInputDelegate {

    @IBOutlet weak var hightCon: NSLayoutConstraint!
    @IBOutlet weak var vtextField: UITextField!
    @IBOutlet weak var stextField: UITextField!
    var rbutton: UIButton!
    
    //#MARK: – Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        // 自定义UINavigationBar
        let nav = UINavigationBar.init(frame: CGRect(x: 0, y: 0, width: KscreenWidth, height: 64))
        UINavigationBar.appearance().barTintColor = UIColor.hexStringToUIColor("#00acff")
        let label = UILabel.init(frame: CGRect(x: 50, y: 20, width: KscreenWidth-120, height: 44))
        
        label.text = "设置服务器地址"
        label.textAlignment = NSTextAlignment.center
        label.textColor = UIColor.white
        label.font = UIFont.systemFont(ofSize: 17)
//        label.backgroundColor = UIColor.redColor()
        let lbutton = UIButton.init(frame: CGRect(x: 15, y: 20, width: 44, height: 44))
        lbutton.setImage(UIImage(named: "返回"), for: UIControlState())
//        lbutton.backgroundColor = UIColor.greenColor()
        lbutton.imageView?.contentMode = UIViewContentMode.scaleAspectFill
        lbutton.addTarget(self, action: #selector(ServerViewController.back), for: UIControlEvents.touchUpInside)
        rbutton = UIButton.init(frame: CGRect(x: KscreenWidth-50, y: 20, width: 44, height: 44))
        rbutton.setImage(UIImage(named: "ic_qr_code"), for: UIControlState())
        rbutton.titleLabel!.font = UIFont.systemFont(ofSize: 16)
//        rbutton.backgroundColor = UIColor.yellowColor()
        rbutton.addTarget(self, action: #selector(ServerViewController.didClickButton), for: UIControlEvents.touchUpInside)
        doneButton.setBackgroundImage(UIImage(named:"矩形-2" ), for: UIControlState.highlighted)
        self.view.addSubview(nav)
        self.view.addSubview(label)
        self.view.addSubview(rbutton)
        self.view.addSubview(lbutton)
       
        
        //用手势收回键盘的方法
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ServerViewController.hideKeyboard))
        self.view.addGestureRecognizer(gestureRecognizer)
        self.view.backgroundColor = UIColor(white: 0.893, alpha: 1.000)
        stextField.text = ConfigGlobal.getRootIP().rootIP
        vtextField.text = ConfigGlobal.getRootIP().IPName
        stextField.delegate = self
        vtextField.delegate = self
        
        NotificationCenter.default.addObserver(self, selector: #selector(ServerViewController.change), name: NSNotification.Name.UITextFieldTextDidChange, object: self.stextField)
        NotificationCenter.default.addObserver(self, selector: #selector(ServerViewController.change), name: NSNotification.Name.UITextFieldTextDidChange, object: self.vtextField)
        NotificationCenter.default.addObserver(self, selector: #selector(ServerViewController.keyboardShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    }
       
    override func viewWillAppear(_ animated: Bool) {
        
        super.viewWillAppear(animated)
        stextField.resignFirstResponder()
        vtextField.resignFirstResponder()
        
        if UserDefaults.standard.bool(forKey: "Login") {
            self.vtextField.isUserInteractionEnabled = false
            self.stextField.isUserInteractionEnabled = false
            self.doneButton.isUserInteractionEnabled = false
            self.rbutton.isUserInteractionEnabled = false
        }
    }
    
    //#MARK: – IBAtions
    
    func keyboardShow(_ textField: UITextField) {
      
        if self.view.bounds.height > 568 {
            
             self.hightCon.constant = 44
        }else{
             self.hightCon.constant = 10
        }
       
         print(self.view.bounds.height)
        
        UIView.animate(withDuration: 0.25, animations: {
            self.view.layoutIfNeeded()
        }, completion: { (finished) in
            
        }) 
    }

    func change() {
        if (vtextField.text?.characters.count > 0 && stextField.text?.characters.count>0) {
            doneButton.isEnabled = true
            doneButton.setBackgroundImage(UIImage(named: "矩形-2"), for: UIControlState())
            doneButton.setTitleColor(UIColor.white, for: UIControlState())
            
        }else{
            doneButton.isEnabled = false
            doneButton.setBackgroundImage(UIImage(named: "矩形-2-拷贝"), for: UIControlState.disabled)
        }
    }

    func back() {
        if UserDefaults.standard.bool(forKey: "Login") {
            
            let  setVC = SetViewController()
            self.present(setVC, animated: true, completion: nil)

        }
        let  loginVC = LoginViewController()
        ConfigGlobal.saveRootIP(stextField.text!, name: self.vtextField.text!)
        self.present(loginVC, animated: true, completion: nil)
    }
    
    @IBAction func doneButton(_ sender: AnyObject) {
        ConfigGlobal.saveRootIP(stextField.text!, name: self.vtextField.text!)
        let loginVC = LoginViewController()
        self.present(loginVC, animated: true, completion: nil)
    }
    
    @IBOutlet weak var doneButton: UIButton!
    func didClickButton(_ sender: AnyObject) {
        AVQRCodeViewManager.shareAVQRCodeViewManager.InputDelegate = self
        AVQRCodeViewManager.showComera()
        self.view.endEditing(true)
    }
    func finishScan(_ msg: String?) {
        AVQRCodeViewManager.shareAVQRCodeViewManager.InputDelegate = nil
        let data = msg?.data(using: String.Encoding.utf8)
        guard data != nil else{
            SVProgressHUD.showError(withStatus: "不能识别服务器地址信息")
            return
        }
        do {
            let dict =  try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
            if  let dictR = dict as? [String : String] {
                    self.stextField.text = dictR["ip"]
                    self.vtextField.text = dictR["servername"]
                UIView.animate(withDuration: 0.5, animations: {
                    self.doneButton.alpha = 0.5
                    }, completion: { (true) in
                        self.doneButton(UIButton())
                })
            }else{
                SVProgressHUD.showError(withStatus: "不能识别服务器地址信息")
            }
        }catch{
            SVProgressHUD.showError(withStatus: "不能识别服务器地址信息")
        }
    }
    func hideKeyboard() {
        self.hightCon.constant = 44
        stextField.resignFirstResponder()
        vtextField.resignFirstResponder()
    }
    
    //#MARK: – UITextFieldDelegate
    func textFieldShouldReturn(_ textField: UITextField) -> Bool{
        stextField.resignFirstResponder()
        vtextField.resignFirstResponder()
        return true
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: "\(ServerViewController.self)", bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
